package com.wxt.blog.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wxt.blog.entity.Blog;
import com.wxt.blog.entity.Comment;
import com.wxt.blog.entity.User;
import com.wxt.blog.service.BlogService;
import com.wxt.blog.service.CommentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/blog/*")
public class BlogController extends HttpServlet {
    
    private final BlogService blogService = new BlogService();

   // 处理点赞/取消点赞的私有方法
   private void handleLike(HttpServletRequest request, HttpServletResponse response, boolean isLike) throws IOException {
       try {
           User user = (User) request.getSession().getAttribute("user");
           if (user == null) {
               // 用户未登录，返回错误信息
               sendJsonResponse(response, false, "请先登录");
               return;
           }

           int blogId = Integer.parseInt(request.getParameter("id"));
           int newLikeCount = blogService.handleLike(blogId, user.getId(), isLike);
           // 返回成功响应
           sendJsonResponse(response, true, "操作成功", newLikeCount);
       } catch (Exception e) {
           sendJsonResponse(response, false, e.getMessage());
       }
   }

   private void sendJsonResponse(HttpServletResponse response, boolean success, String message) throws IOException {
       sendJsonResponse(response, success, message, 0);
   }

    private void sendJsonResponse(HttpServletResponse response, boolean success, String message, int likeCount) throws IOException {
        response.setContentType("application/json;charset=UTF-8");

        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("success", success);
        responseMap.put("message", message);
        responseMap.put("likeCount", likeCount);

        String json = new ObjectMapper().writeValueAsString(responseMap);
        response.getWriter().write(json);
    }

    // 处理POST请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getRequestURI().substring(request.getContextPath().length());
        System.out.println("请求路径：" + path); 

        // 处理保存博客的请求
        if ("/blog/save".equals(path)) {
            // 获取当前登录用户
            User author = (User) request.getSession().getAttribute("user");
            if (author == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }

            // 获取表单数据
            String title = request.getParameter("title");
            String content = request.getParameter("content");

            // 创建Blog对象
            Blog blog = new Blog();
            blog.setTitle(title);
            blog.setContent(content);
            blog.setUserId(author.getId());

            // 调用Service保存
            blogService.saveBlog(blog);

            // 保存成功后重定向到博客列表页
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
        // 处理查看我的博客的请求
        if ("/blog/my".equals(path)) {
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }

            // 查询该用户的博客
            List<Blog> myBlogs = blogService.findBlogsByUserId(user.getId());
            request.setAttribute("myBlogs", myBlogs);

            request.getRequestDispatcher("/my-blogs.jsp").forward(request, response);
        }

        // 添加更新处理
        if ("/blog/update".equals(path)) {
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }

            // 获取请求参数
            int blogId = Integer.parseInt(request.getParameter("id"));
            String title = request.getParameter("title");
            String content = request.getParameter("content");

            // 创建Blog对象并设置属性
            Blog blog = new Blog();
            blog.setId(blogId);
            blog.setTitle(title);
            blog.setContent(content);
            blog.setUserId(user.getId());

            boolean success = blogService.updateBlog(blog);

            if (success) {
                response.sendRedirect(request.getContextPath() + "/blog/detail?id=" + blogId);
            } else {
                request.setAttribute("error", "更新失败");
                request.getRequestDispatcher("/edit-blog.jsp").forward(request, response);
            }
        }

        // 点赞/取消点赞处理
        if ("/blog/like".equals(path)) {
            response.setContentType("application/json");
            PrintWriter out = response.getWriter();

            try {
                User user = (User) request.getSession().getAttribute("user");
                if (user == null) {
                    out.write("{\"success\":false,\"message\":\"请先登录\"}");
                    return;
                }

                // 获取博客ID
                int blogId = Integer.parseInt(request.getParameter("id"));
                // 调用Service处理点赞
                blogService.likeBlog(blogId, user.getId());

                out.write("{\"success\":true}");
            } catch (Exception e) {
                e.printStackTrace();
                out.write("{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
            }
        }
    }

    // 添加doGet方法
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getRequestURI().substring(request.getContextPath().length());

        // 处理查看我的博客的GET请求
        if ("/blog/my".equals(path)) {
            // 获取当前登录用户
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }

            // 查询该用户的博客
            List<Blog> myBlogs = blogService.findBlogsByUserId(user.getId());
            request.setAttribute("myBlogs", myBlogs);

            // 转发到my-blogs.jsp
            request.getRequestDispatcher("/my-blogs.jsp").forward(request, response);
        }

        // 处理查看博客详情的请求
        if ("/blog/detail".equals(path)) {
            try {
                // 获取博客ID（原有错误处理保留）
                String idParam = request.getParameter("id");
                if (idParam == null || !idParam.matches("\\d+")) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid blog ID");
                    return;
                }
                int blogId = Integer.parseInt(idParam);

                // 查询博客详情（原有逻辑保留）
                Blog blog = blogService.findBlogById(blogId);
                if (blog == null) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "Blog not found");
                    return;
                }

                // 加载评论列表
                List<Comment> comments = new CommentService().getCommentsByBlogId(blogId);
                request.setAttribute("comments", comments);

                // 增加浏览量（原有逻辑保留）
                blogService.incrementViewCount(blogId);

                // 将博客对象存入request属性并转发到详情页
                request.setAttribute("blog", blog);
                request.getRequestDispatcher("/blog-detail.jsp").forward(request, response);

            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }

        // 添加删除处理
        if ("/blog/delete".equals(path)) {
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }

            // 获取要删除的博客ID
            int blogId = Integer.parseInt(request.getParameter("id"));
            Blog blog = blogService.findBlogById(blogId);

            // 权限验证：检查当前用户是否是博客作者
            if (blog == null || !blog.getUserId().equals(user.getId())) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            // 执行删除
            boolean success = blogService.deleteBlog(blogId);

            if (success) {
                response.sendRedirect(request.getContextPath() + "/blog/my"); // 删除后返回我的博客列表
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }

        // 添加编辑处理
        if ("/blog/edit".equals(path)) {
            // 获取当前登录用户
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }

            // 获取要编辑的博客ID
            int blogId = Integer.parseInt(request.getParameter("id"));
            Blog blog = blogService.findBlogById(blogId);

            // 验证当前用户是否是作者
            if (blog == null || !blog.getUserId().equals(user.getId())) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            // 将博客对象存入request属性并转发到编辑页
            request.setAttribute("blog", blog);
            request.getRequestDispatcher("/edit-blog.jsp").forward(request, response);
        }

        // 处理搜索博客的请求
        if ("/blog/search".equals(path)) {
            String keyword = request.getParameter("keyword");
            List<Blog> searchResults = blogService.searchBlogs(keyword);

            request.setAttribute("blogs", searchResults);
            request.setAttribute("searchKeyword", keyword);
            request.getRequestDispatcher("/search-results.jsp").forward(request, response);
            return;
        }
    }
}